package com.xy.modular.owner.controller;

import com.alibaba.fastjson.JSONObject;
import com.xy.framework.base.controller.BaseController;
import com.xy.framework.mreturn.MReturnObject;
import com.xy.framework.mreturn.MReturnUntil;
import com.xy.framework.util.HttpUtils;
import com.xy.framework.util.JsonUntils;
import com.xy.framework.util.uuid.UUIDUtils;
import com.xy.modular.basics.action.LoginController;
import com.xy.modular.basics.service.IUserService;
import com.xy.modular.owner.model.OwnerAuthLocal;
import com.xy.modular.owner.model.OwnerAuthThird;
import com.xy.modular.owner.service.IOwnerAuthLocalService;
import com.xy.modular.owner.service.IOwnerAuthThirdService;
import io.swagger.annotations.Api;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import java.io.UnsupportedEncodingException;

@Api(description = "登录相关接口")
@Controller
@RequestMapping("/wx/login")
public class WxLoginController extends BaseController {

	static Logger log = LoggerFactory.getLogger(LoginController.class);

	@Resource
	private IUserService userService;

	@Resource
	private IOwnerAuthThirdService ownerAuthThirdService;
	@Resource
	private IOwnerAuthLocalService ownerAuthLocalService;

	// GET
	// https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=APPID&secret=APPSECRET
	// https://api.weixin.qq.com/sns/jscode2session?appid=APPID&secret=SECRET&js_code=JSCODE&grant_type=authorization_code
	private String APPID = "wx895b629ee0340df3";
	private String SECRET = "981f31ef6dfb02697c9c0b377e36687a";
	private String CODE_URL = "https://api.weixin.qq.com/sns/jscode2session";
	private String GET_TOKEN_URL = "https://api.weixin.qq.com/cgi-bin/token";

	/**
	 * 登录凭证校验。通过 wx.login 接口获得临时登录凭证 code 后传到开发者服务器调用此接口完成登录流程。
	 * auth.code2Session 登录
	 * 
	 * @param code
	 * @return
	 * @throws UnsupportedEncodingException
	 */
	@RequestMapping(value = "/code2Session/{code}")
	public @ResponseBody MReturnObject code2Session(@PathVariable("code") String code, OwnerAuthLocal ownerAuthLocal)
			throws UnsupportedEncodingException {
		String str = HttpUtils.doGet(CODE_URL + "?appid=" + APPID + "&secret=" + SECRET + "&js_code=" + code
				+ "&grant_type=authorization_code", "utf-8");
		System.out.println("-------------------------" + code);
		System.out.println(str);
		JSONObject json = JsonUntils.stringToJson(str);
		OwnerAuthThird ownerAuth = ownerAuthThirdService.getByOpenid(json.getString("openid"));
		if (ownerAuth != null) {
			return new MReturnObject(MReturnObject.SUCCESS, ownerAuthLocalService.getByIdNP(ownerAuth.getAuthId()));
		} else {
			ownerAuth=new OwnerAuthThird(json.getString("openid"),json.getString("session_key") , "weixin");
			ownerAuthLocal.setAuthId(UUIDUtils.UUID());
			ownerAuthLocalService.save(ownerAuthLocal);
			ownerAuth.setAuthId(ownerAuthLocal.getAuthId());
			ownerAuthThirdService.save(ownerAuth);
			return new MReturnObject(MReturnObject.SUCCESS, ownerAuthLocalService.getByIdNP(ownerAuth.getAuthId()));
		}
	}

	// https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=APPID&secret=APPSECRET
	/**
	 * 获取小程序全局唯一后台接口调用凭据（access_token）。调调用绝大多数后台接口时都需使用
	 * access_token，开发者需要进行妥善保存。 auth.getAccessToken 接口调用凭据
	 * 
	 * @param code
	 * @return
	 * @throws UnsupportedEncodingException
	 */
	@RequestMapping(value = "/getAccessToken/{session_key}")
	public @ResponseBody MReturnObject getAccessToken(@PathVariable("sessionKey") String session_key)
			throws UnsupportedEncodingException {
		String str = HttpUtils.doGet(
				GET_TOKEN_URL + "?grant_type=client_credential&appid=" + APPID + "&secret=" + session_key, "utf-8");
		return new MReturnObject(MReturnObject.SUCCESS, JsonUntils.stringToJson(str));
	}

	@RequestMapping(value = "/userInfo/{userId}", method = RequestMethod.GET)
	public @ResponseBody MReturnObject userInfo(@PathVariable("userId") String userId) {
		return new MReturnObject(MReturnObject.SUCCESS, ownerAuthLocalService.getByIdNP(userId));
	}
	@RequestMapping(value = "/error", method = RequestMethod.GET)
	public @ResponseBody MReturnObject loginError(Model model) {
		return new MReturnObject(MReturnObject.ERROR, MReturnUntil.WARNING_NOT_LOGIN);
	}

	@RequestMapping(value = "/logout", method = RequestMethod.GET)
	public @ResponseBody MReturnObject timeOut(Model model) {
		return new MReturnObject(MReturnObject.SUCCESS, "success");
	}
}
